package net.sudot.commons.security;

import net.sudot.chess.business.model.User;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.cache.CacheManager;

/**
 * 授权域
 *
 * @author tangjialin on 2017-06-14 0014.
 */
public class SocialUserAuthorizingRealm extends AuthorizingRealm {

    public SocialUserAuthorizingRealm(AuthenticationProvider authenticationProvider) {
        super(authenticationProvider);
    }

    public SocialUserAuthorizingRealm(CacheManager cacheManager, AuthenticationProvider authenticationProvider) {
        super(cacheManager, authenticationProvider);
    }

    public SocialUserAuthorizingRealm(CredentialsMatcher matcher, AuthenticationProvider authenticationProvider) {
        super(matcher, authenticationProvider);
    }

    public SocialUserAuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher, AuthenticationProvider authenticationProvider) {
        super(cacheManager, matcher, authenticationProvider);
    }

    /**
     * 执行获取认证信息的操作(即:进行身份认证的操作)
     *
     * @param authenticationToken 令牌
     * @return 认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        SocialUserAuthenticationToken token = (SocialUserAuthenticationToken) authenticationToken;
        User user = authenticationProvider.getUser(token.getSocialUser());
        if (user == null) { throw new UnknownAccountException(); }
        if (!Boolean.TRUE.equals(user.getEnabled())) { throw new DisabledAccountException(); }
        if (Boolean.TRUE.equals(user.getLocked())) { throw new LockedAccountException(); }
        return new SimpleAccount(user, authenticationToken.getCredentials(), getName());
    }

}